<template>
    <view class="container">
        <!-- 分类信息头部 -->
        <view class="category-header" v-if="category">
            <view class="category-info">
                <text class="category-name">{{ category.name || '加载中...' }}</text>
                <text class="category-count">{{ category.count || 0 }} 篇文章</text>
            </view>
            <rich-text class="category-desc" :nodes="category.description"
                v-if="category && category.description"></rich-text>
        </view>

        <!-- 文章列表 - 网格布局 -->
        <view class="article-grid" v-if="articles.length">
            <view class="article-card" v-for="(article, index) in articles" :key="index" @tap="goToDetail(article)">
                <image class="card-image" :src="getPostImage(article)" mode="aspectFill" lazy-load />
                <view class="card-content">
                    <text class="card-title">{{ formatTitle(article.title.rendered) }}</text>
                    <view class="card-meta">
                        <text class="card-date">{{ formatDate(article.date) }}</text>
                        <view class="category-tags" v-if="article.categories && article.categories.length">
                            <text class="category-tag" v-for="(catId, idx) in article.categories" :key="idx"
                                v-if="getCategoryName(catId)">
                                {{ getCategoryName(catId) }}
                            </text>
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <!-- 加载状态 -->
        <view class="loading-box" v-if="loading">
            <view class="loading">
                <view class="loading-spinner"></view>
                <text>加载中...</text>
            </view>
        </view>

        <!-- 没有更多 -->
        <view class="no-more" v-if="noMore && articles.length">
            <text>没有更多内容了</text>
        </view>

        <!-- 空状态 -->
        <view class="empty-state" v-if="!loading && !articles.length">
            <text>该分类下暂无文章</text>
        </view>

        <!-- 返回顶部按钮 -->
        <view class="back-to-top" v-if="showBackToTop" @tap="backToTop">
            <uni-icons type="top" size="20" color="#fff"></uni-icons>
        </view>
    </view>
</template>
  
<script>
import api from '@/api/wordpress'

export default {
    data() {
        return {
            categoryId: null,
            category: null,
            articles: [],
            page: 1,
            loading: false,
            noMore: false,
            categories: {},
            showBackToTop: false,
            scrollTop: 0
        }
    },

    async onLoad(options) {
        if (options.id) {
            this.categoryId = options.id;
            await Promise.all([this.getCategories(), this.getCategoryDetail(), this.getCategoryPosts()]);
        }
    },

    onPullDownRefresh() {
        this.refreshList();
    },

    onReachBottom() {
        if (!this.loading && !this.noMore) {
            this.page++;
            this.getCategoryPosts();
        }
    },

    onPageScroll(e) {
        this.showBackToTop = e.scrollTop > 500;
        this.scrollTop = e.scrollTop;
    },

    methods: {
        async getCategoryDetail() {
            try {
                const res = await api.getCategoryDetail(this.categoryId);
                if (res.statusCode === 200) {
                    this.category = res.data;
                    uni.setNavigationBarTitle({ title: res.data.name });
                }
            } catch (e) {
                console.error('获取分类详情失败:', e);
            }
        },

        async getCategoryPosts() {
            if (this.loading || (this.noMore && this.page > 1)) return;

            this.loading = true;
            try {
                const res = await api.getCategoryPosts(this.categoryId, this.page);
                if (res.statusCode === 200) {
                    const newArticles = res.data.map(article => ({
                        ...article,
                        imageUrl: api.getPostImage(article)
                    }));

                    this.articles = this.page === 1 ? newArticles : [...this.articles, ...newArticles];
                    this.noMore = newArticles.length < 10;
                }
            } catch (e) {
                console.error('获取分类文章失败:', e);
            } finally {
                this.loading = false;
            }
        },

        async refreshList() {
            this.page = 1;
            this.noMore = false;
            this.articles = [];
            await Promise.all([this.getCategories(), this.getCategoryDetail(), this.getCategoryPosts()]);
            uni.stopPullDownRefresh();
        },

        formatTitle(title) {
            return title
                .replace(/&#8211;/g, '-')
                .replace(/&amp;/g, '&')
                .replace(/&#8220;/g, '"')
                .replace(/&#8221;/g, '"')
                .replace(/&#8216;/g, "'")
                .replace(/&#8217;/g, "'");
        },

        formatDate(date) {
            const d = new Date(date);
            return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
        },

        getPostImage(article) {
            return article.imageUrl || api.getPostImage(article);
        },

        async getCategories() {
            try {
                const res = await api.getCategories();
                if (res.statusCode === 200 && res.data) {
                    this.categories = res.data.reduce((acc, cat) => {
                        acc[cat.id] = cat.name;
                        return acc;
                    }, {});
                }
            } catch (e) {
                console.error('获取分类失败:', e);
            }
        },

        getCategoryName(catId) {
            return this.categories[catId] || '';
        },

        goToDetail(article) {
            uni.navigateTo({
                url: `/pages/detail/detail?id=${article.id}&title=${encodeURIComponent(article.title.rendered)}`
            });
        },

        backToTop() {
            uni.pageScrollTo({
                scrollTop: 0,
                duration: 300
            });
        }
    }
}
</script>
  
<style>
.container {
    padding: 20rpx;
    min-height: 100vh;
    background-color: #f5f6fa;
}

/* 分类头部样式 */
.category-header {
    background: #fff;
    padding: 40rpx 30rpx;
    margin-bottom: 20rpx;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.category-info {
    display: flex;
    align-items: baseline;
    gap: 16rpx;
    margin-bottom: 16rpx;
}

.category-name {
    font-size: 40rpx;
    font-weight: bold;
    color: #333;
}

.category-count {
    font-size: 26rpx;
    color: #999;
}

.category-desc {
    font-size: 28rpx;
    color: #666;
    line-height: 1.6;
}

/* 网格布局样式 */
.article-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20rpx;
    padding: 10rpx;
}

.article-card {
    background: #fff;
    border-radius: 16rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
    transition: transform 0.2s;
}

.article-card:active {
    transform: scale(0.98);
}

.card-image {
    width: 100%;
    height: 200rpx;
    object-fit: cover;
}

.card-content {
    padding: 20rpx;
}

.card-title {
    font-size: 28rpx;
    font-weight: 500;
    color: #333;
    line-height: 1.4;
    margin-bottom: 16rpx;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.card-meta {
    display: flex;
    flex-direction: column;
    gap: 8rpx;
}

.card-date {
    font-size: 24rpx;
    color: #999;
}

.category-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8rpx;
}

.category-tag {
    font-size: 20rpx;
    color: #ff5722;
    background-color: rgba(255, 87, 34, 0.1);
    padding: 4rpx 12rpx;
    border-radius: 20rpx;
}

/* 加载状态样式 */
.loading-box {
    padding: 40rpx 0;
    text-align: center;
}

.loading {
    display: inline-flex;
    align-items: center;
}

.loading-spinner {
    width: 40rpx;
    height: 40rpx;
    border: 4rpx solid #f3f3f3;
    border-top: 4rpx solid #ff5722;
    border-radius: 50%;
    margin-right: 16rpx;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

/* 空状态样式 */
.empty-state {
    padding: 100rpx 0;
    text-align: center;
    color: #999;
    font-size: 28rpx;
}

/* 返回顶部按钮样式 */
.back-to-top {
    position: fixed;
    right: 40rpx;
    bottom: 120rpx;
    width: 80rpx;
    height: 80rpx;
    background-color: #ff5722;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4rpx 16rpx rgba(255, 87, 34, 0.3);
    z-index: 999;
}

/* 没有更多样式 */
.no-more {
    text-align: center;
    padding: 30rpx 0;
    color: #999;
    font-size: 24rpx;
}
</style>
